package com.gin.no_gay_alliance.fragment.forum;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.gin.nga.callback.JsonCallback;
import com.gin.nga.method.ForumApi;
import com.gin.nga.params.forum.ForumParam;
import com.gin.nga.response.body.ForumBody;
import com.gin.no_gay_alliance.adpter.SearchHistoryAdapter;
import com.gin.no_gay_alliance.adpter.forum.ForumSearchResultAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.databinding.FragmentForumSearchBinding;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.manager.history.SearchHistoryManager;
import com.gin.no_gay_alliance.utils.EditTextUtils;
import com.gin.no_gay_alliance.utils.InputMethodManagerUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.ForumSearchResult;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 搜索版面
 */
public class ForumSearchFragment extends BaseBindingFragment<FragmentForumSearchBinding> implements TextView.OnEditorActionListener, SearchHistoryAdapter.OnKeywordSelectedListener {
    ForumSearchResultAdapter adapter;
    private SearchHistoryAdapter searchHistoryAdapter;

    /**
     * onCreateView 的后续操作
     */
    @Override
    protected void onCreateView() {
        adapter = new ForumSearchResultAdapter(requireContext());
        b.recyclerView.setAdapter(adapter);
        b.btSearch.setOnClickListener(this);
        b.et.setOnEditorActionListener(this);

        // 装载搜索历史
        searchHistoryAdapter = new SearchHistoryAdapter(requireContext(), SearchHistoryManager.DATA_STORE_KEY_SEARCH_FORUM_HISTORY, this);
        b.rvSearchHistory.setAdapter(searchHistoryAdapter);
        b.tvClearHistory.setOnClickListener(this);

        // 根据是否获得焦点决定控件显示状态
        b.et.setOnFocusChangeListener((v, hasFocus) -> {
            Log.d(TAG, "hasFocus: " + hasFocus);
            if (hasFocus) {
                showHistory(true);
                showResult(false);
            } else {
                showHistory(false);
                showResult(true);
            }
        });
    }

    /**
     * 点击事件
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        if (v == b.btSearch) {
            sendRequest();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        EditTextUtils.focusSelect(requireActivity(), b.et, handler);
    }

    @Override
    public void onPause() {
        super.onPause();
        InputMethodManagerUtils.hide(b.et);
    }

    /**
     * 输入框的动作响应
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            sendRequest();
            return true;
        }
        return false;
    }

    /**
     * 选中关键字时的回调
     *
     * @param keyword 被选中的关键字
     */
    @Override
    public void onKeywordSelected(String keyword) {
        b.et.setText(keyword);
        sendRequest();
    }

    private void sendRequest() {
        // 取消焦点
        b.et.clearFocus();
        InputMethodManagerUtils.hide(b.et);
        // 点击搜索
        String keyword = b.et.getText().toString();
        // 记录搜索历史
        searchHistoryAdapter.add(keyword);
        ForumApi.search(MyApplication.getClient(), new ForumParam(keyword)).async(new JsonCallback<ForumBody>() {
            @Override
            public void onSuccess(ForumBody body) {
                List<ForumSearchResult> results = body.values().stream().map(ForumSearchResult::new).collect(Collectors.toList());
                ui(() -> adapter.updateData(results));
            }
        });
    }

    /**
     * 搜索历史相关控件显示
     */
    private void showHistory(boolean show) {
        ViewUtils.setGone(!show, b.rvSearchHistory, b.tvClearHistory, b.tvSearchHistory);
    }

    /**
     * 搜索结果相关控件显示
     */
    private void showResult(boolean show) {
        ViewUtils.setGone(!show, b.recyclerView, b.tvForum, b.tvFrom);
    }
}